//
//  MCWithdrawMoneyViewController.swift
//  StoreManage
//
//  Created by MC on 2017/12/27.
//  Copyright © 2017年 MC. All rights reserved.
//

import UIKit

class MCWithdrawMoneyViewController: MCViewController {

    
    private var pageNumber = 1
    private var phone = ""
    private var money : NSNumber = 0
    
    private var moneyTextField : UITextField?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        baseSetting()
        
        initUI()
        
        sendNetworking()
    }
    
    // MARK: - System Delegate
    
    // MARK: - Custom Delegate
    
    // MARK: - Action
    
    @objc func rightItemClicked() {
        
        let str = "tel:" + phone
        
        let callWebView = UIWebView()
        let request = NSURLRequest.init(url: URL.init(string: str)!)
        callWebView.loadRequest(request as URLRequest)
        view.addSubview(callWebView)
    }
    
    
    @objc func saveButtonClecked() {
        
        
        
        let alter = UIAlertController.init(title: "申请提现", message: "提现金额不少于100元", preferredStyle: UIAlertControllerStyle.alert)
      
        alter.addTextField(configurationHandler: { (textField) in
            textField.font = MCFont(14)
            textField.keyboardType = UIKeyboardType.decimalPad
            self.moneyTextField = textField
        })
        let cancle = UIAlertAction.init(title: "取消", style: UIAlertActionStyle.cancel) { (a) in }
        let confirm = UIAlertAction.init(title: "确定", style: UIAlertActionStyle.default) { (b) in
            
            let wantDrawMoney = Int((self.moneyTextField?.text!)!)!*100
            
            
            if self.money.intValue < wantDrawMoney {
                MCHUD_text(message: "提现金额超出账号余额", view: self.view, delay: 1.5)
                return
            }
            
            
            let para = [
                "money" : wantDrawMoney
                ] as [String : Any]
            
            MCNetwork_post(url: JAVA_storeDraw, para: para as [String : AnyObject], vc: self,hudSuperView: nil,isHiddenTabbar: true, success: { (response) in

                
                let endMoney = self.money.intValue - Int((self.moneyTextField?.text!)!)!*100
                self.headView.moneyLabel.text = "账号余额: " + MCString_judgemantDecimalsIsZero(figure: endMoney)
                
                MCAlterController_oneOptions(vc: self, message: "平台已收到您的提现申请，会在1~2个工作日内转入入驻账号，如有更改账号或者其他问题，请联系客服", cancle: {
                    
                })
                
                
            }, dislike: { (response) in }) { (error) in }
        }
        alter.addAction(confirm)
        alter.addAction(cancle)
        self.present(alter, animated: true, completion: nil)
    }
    
    // MARK: - Network
    func sendNetworking() {
        let para = [
            "pageNum" : pageNumber
            ] as [String : Any]
        
        MCNetwork_post(url: JAVA_storeJournal, para: para as [String : AnyObject], vc: self,hudSuperView: self.view,isHiddenTabbar: true, success: { (response) in
            
            
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            if self.pageNumber == 1 {
                self.dataArrayM.removeAllObjects()
            }

            
            let dataDict = response["data"] as! [String : AnyObject]
            let userInfo = dataDict["userInfo"] as! [String:Any]
            
            self.money = userInfo["money"] as! NSNumber
            let picture = userInfo["picture"] as! String
            let accountNo = userInfo["accountNo"] as! String
            self.phone = userInfo["notice"] as! String
            
            
            self.headView.nameLabel.text = "账号：\n" + accountNo
            self.headView.moneyLabel.text = "账号余额: " + MCString_judgemantDecimalsIsZero(figure: self.money.intValue)
            self.headView.iconImageView.sd_setImage(with: URL.init(string: picture), placeholderImage: #imageLiteral(resourceName: "Reuse_placeholder_1_1"))
            
            let journal = dataDict["journal"] as! NSArray
            
            
            if journal.count + self.dataArrayM.count == 0 {
                self.tableView.showBgImage()
            } else {
                self.tableView.hideBgImage()
                for dict in journal {
                    let model = MCWithdrawMoneyModel()
                    model.setValuesForKeys(dict as! [String:Any])
                    self.dataArrayM.add(model)
                }
                self.tableView.reloadData()
            }
        }, dislike: { (response) in }) { (error) in }
    }
    
    // MARK: - Method
    func baseSetting() {
        self.title = "提现"
        self.view.backgroundColor = UIColor.white
        
        
        navigationItem.rightBarButtonItem = MCSetBarButtonItem_text("联系客服", target: self, selector: #selector(rightItemClicked))
        
        self.tableView.mj_header = MCRefreshHeader.init(refreshingBlock: {
            self.pageNumber = 1
            self.sendNetworking()
        })
        
        self.tableView.mj_footer = MCRefreshFooter.init(refreshingBlock: {
            self.pageNumber += 1
            self.sendNetworking()
        })
    }
    
    func initUI() {
        view.addSubview(tableView)
        tableView.snp.remakeConstraints { (make) ->Void in
            make.edges.equalTo(view).inset(UIEdgeInsetsMake(0, 0, 44, 0))
        }
        
        tableView.tableHeaderView = headView
        
        view.addSubview(saveButton)
        saveButton.snp.remakeConstraints { (make) ->Void in
            make.left.right.bottom.equalTo(view)
            make.height.equalTo(44)
        }
    }
    
    // MARK: - Setter & Getter
    lazy private var tableView: MCTableView = {
        let tableView = MCTableView.init(frame: CGRect.zero, style: UITableViewStyle.plain)
        tableView.delegate = self
        tableView.dataSource = self
        return tableView
    }()
    
    lazy var dataArrayM: NSMutableArray = {
        let arrayM = NSMutableArray()
        return arrayM
    }()
    
    lazy var headView: MCWithdrawMoneyHeaderView = {
        let view = MCWithdrawMoneyHeaderView()
        return view
    }()

    lazy var saveButton: UIButton = {
        let button = UIButton.init(type: UIButtonType.custom)
        button.backgroundColor = UIColor.MCMain
        button.titleLabel?.font = MCFont(16)
        button.setTitle("提现", for: UIControlState.normal)
        button.setTitleColor(UIColor.white, for: UIControlState.normal)
        button.addTarget(self, action: #selector(saveButtonClecked), for: UIControlEvents.touchUpInside)
        return button
    }()
}

extension MCWithdrawMoneyViewController : UITableViewDelegate,UITableViewDataSource {
    
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArrayM.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = MCWithdrawMoneyCell.init(style: UITableViewCellStyle.value1, reuseIdentifier: "cell")
        cell.selectionStyle = UITableViewCellSelectionStyle.none
        cell.model = self.dataArrayM[indexPath.row] as! MCWithdrawMoneyModel
        return cell
    }
}
